package org.gdpu.action;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.gdpu.Service.ExpenseService;
import org.gdpu.model.Expense;
import org.gdpu.util.ExcelUtil;
import org.gdpu.vo.ExpenseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 14-3-6
 * Time: 下午2:45
 * To change this template use File | Settings | File Templates.
 */
@Component("expense")
@Scope("prototype")
public class ExpenseAction extends MyActionSupport implements ModelDriven<ExpenseVO> {

    @Qualifier("excelUtil")
    @Autowired
    private ExcelUtil excelUtil;
    private ExpenseService expenseService;
    private final ExpenseVO expenseVO = new ExpenseVO();
    private final static Logger logger = LogManager.getLogger(StudentAction.class);

    public String findExpenseByDormitoryId() {
        if (expenseVO.getDormitoryId().isEmpty()) {
            expenseVO.setResultMessage("<script>alert('请输入宿舍编号！');location.href='/page/expenseManagement/findExpenseById.jsp';</script>");
            return ERROR;
        }
        else if(expenseVO.getDormitoryId().length() != 4){
            expenseVO.setResultMessage("<script>alert('请输入4位宿舍编号！');location.href='/page/expenseManagement/findExpenseById.jsp';</script>");
            return ERROR;
        }

        Expense expense = expenseService.findExpense(expenseVO.getDormitoryId(),expenseVO.getCampus());
        if (expense == null) {
            expenseVO.setResultMessage("<script>alert('宿舍编号不存在！');location.href='/page/expenseManagement/findExpenseById.jsp';</script>");
            return ERROR;
        }
        expenseVO.getExpenses().add(expense);
        logger.info("find student by dormitoryId:" + expenseVO.getDormitoryId());
        view = "/page/expenseManagement/findExpenseById.jsp";
        return VIEW;
    }


    public String resumeExpense() {
        try {
            if (expenseVO.getFileName().isEmpty()) {
                expenseVO.setResultMessage("<script>alert('请选择文件！');location.href='/page/expenseManagement/updateExpense.jsp';</script>");
                return ERROR;
            }
            List<Expense> exs = new ArrayList<Expense>();
            List<Object> obj = excelUtil.readExcelByPath(expenseVO.getFileName(),Expense.class, 1, 0);
            for (int i = 0; i < obj.size(); i++) {
                exs.add((Expense) obj.get(i));
            }
            int count = 0;
            String campus = exs.get(0).getDormitory().getCampus().getCampusName();
            String term = exs.get(0).getTerm();
            for (Expense expense : exs) {
                Expense temp = new Expense();
                if((temp = expenseService.findExpense(expense.getDormitory().getDormitoryId(),
                        expense.getDormitory().getCampus().getCampusName())) == null){
                    expenseService.save(expense);
                    ++count;
                }
                else{
                    temp.setElectricRate(expense.getElectricRate());
                    temp.setWaterRate(expense.getWaterRate());
                    temp.setTerm(expense.getTerm());
                    expenseService.update(temp);
                    ++count;
                }
            }
            expenseVO.setResultMessage("成功更新"+term+campus+"学生宿舍费用信息，共有"+obj.size()+"条记录，成功导入"+count+"条记录，请查看数据库。");
            logger.trace("update the expense records success");
            return SUCCESS;
        } catch (RuntimeException e) {
            expenseVO.setResultMessage(e.getMessage());
            logger.error(e);
            return ERROR;
        }
    }

    @Resource(name = "expenseServiceImpl")
    public void setExpenseService(ExpenseService expenseService) {
        this.expenseService = expenseService;
    }

    @Override
    public ExpenseVO getModel() {
        return expenseVO;
    }
}
